﻿#include "menudialog.h"
#include "ui_menudialog.h"

MenuDialog::MenuDialog(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::MenuDialog)
{
    ui->setupUi(this);

    connect(ui->m_btnCancel, &QPushButton::clicked, this, &MenuDialog::on_cancel);
    connect(ui->m_btnSubmit, &QPushButton::clicked, this, &MenuDialog::on_submit);
}

MenuDialog::~MenuDialog()
{
    delete ui;
}

void MenuDialog::init(Menu menu)
{
    if(menu.isMenuBar == 0)
    {
       ui->m_radioMenu0->setChecked(true);
    }
    if(menu.isToolBar == 0)
    {
        ui->m_radioToolbar0->setChecked(true);
    }
    ui->m_menuName->setText(menu.menuName);
    m_menu = menu;
}

void MenuDialog::on_cancel()
{
    reject();
}

void MenuDialog::on_submit()
{
    if(QMessageBox::question(this,
                             QString::fromLocal8Bit("提示"),
                             QString::fromLocal8Bit("请确认操作"),
                             QString::fromLocal8Bit("取消"),
                             QString::fromLocal8Bit("确认")) != 1)
    {
        return;
    }

    QSqlDatabase database = QSqlDatabase::database(DbUtil::SQLITE_CONNECTION_NAME, true);
    if (database.open())
    {
        QSqlQuery sql_query(database);
        if(m_menu.op == "ADD")
        {
            QString sql = QString("insert into t_menu(menu_name, pmenu_id, is_menubar, is_toolbar) "
                                  "values('%1', %2, %3, %4)")
                    .arg(ui->m_menuName->text())
                    .arg(m_menu.pMenuId)
                    .arg(ui->m_radioMenu0->isChecked() ? 0 : 1)
                    .arg(ui->m_radioToolbar0->isChecked() ? 0 : 1);
            qDebug() << sql;
            if(sql_query.exec(sql))
            {
                qDebug() << "insert t_menu " << ui->m_menuName->text();
            }
        }

        if(m_menu.op == "EDIT")
        {
            QString sql = QString("update t_menu set menu_name = '%1', is_menubar = %2, is_toolbar = %3 "
                                  "where menu_id = %4")
                    .arg(ui->m_menuName->text())
                    .arg(ui->m_radioMenu0->isChecked() ? 0 : 1)
                    .arg(ui->m_radioToolbar0->isChecked() ? 0 : 1)
                    .arg(m_menu.menuId);
            qDebug() << sql;
            if(sql_query.exec(sql))
            {
                qDebug() << "update t_role " << ui->m_menuName->text();
            }
        }

    }
    accept();
}
